package com.sy.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sy.dto.AdminInfo;
import com.sy.dto.ClassTabInfo;
import com.sy.dto.StudentTabInfo;
import com.sy.dto.Table;
import com.sy.entity.*;
import com.sy.exception.BusinessException;
import com.sy.service.AdminService;
import com.sy.service.HomeworkService;
import com.sy.vo.AddNoticeVo;
import com.sy.vo.AdminInfoVo;
import com.sy.vo.EditNoticeVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

import static com.sy.constant.RegConstant.PHONE_REGEX;
import static org.springframework.http.HttpStatus.BAD_REQUEST;


@Service
public class AdminServiceImpl extends BaseServiceImpl implements AdminService {



    @Autowired
    protected HomeworkService homeworkService;

    @Override
    public AdminInfo getAdminInfo(String id) {
        if (StringUtils.isBlank(id)) {
            buildError(BAD_REQUEST, "ID不能为空！");
        }
        return adminMapper.getAdminInfoById(id);
    }

    @Override
    public boolean updateAdminInfo(AdminInfoVo adminInfoVo) {
        String id = adminInfoVo.getId();
        String name = adminInfoVo.getName();
        String phone = adminInfoVo.getPhone();

        if (StringUtils.isBlank(id)) {
            buildError(BAD_REQUEST, "ID不能为空！");

        }
        if (StringUtils.isBlank(id)) {
            buildError(BAD_REQUEST, "ID不能为空！");
        }
        if (!phone.matches(PHONE_REGEX)) {
            buildError(BAD_REQUEST, "手机号格式不合法");
        }
        if( StringUtils.isBlank(id)) {
            buildError(BAD_REQUEST, "ID不能为空！");
            if (StringUtils.isBlank(id)) {
                buildError(BAD_REQUEST, "ID不能为空！");
            }
            if (!phone.matches(PHONE_REGEX)) {
                buildError(BAD_REQUEST, "手机号格式不合法");
            }
        if( StringUtils.isBlank(id)) {
            buildError(BAD_REQUEST, "ID不能为空！");
            if (StringUtils.isBlank(id)) {
                buildError(BAD_REQUEST, "ID不能为空！");
            }
            if (!phone.matches(PHONE_REGEX)) {
                buildError(BAD_REQUEST, "手机号格式不合法");
            }
        if (StringUtils.isBlank(id)) {
            buildError(BAD_REQUEST, "ID不能为空！");
            if (StringUtils.isBlank(id)) {
                buildError(BAD_REQUEST, "ID不能为空！");
            }
            if (!phone.matches(PHONE_REGEX)) {
                buildError(BAD_REQUEST, "手机号格式不合法");
            }

            adminMapper.updateAdminInfo(adminInfoVo);
        }
            adminMapper.updateAdminInfo(adminInfoVo);
        }
            adminMapper.updateAdminInfo(adminInfoVo);

        }
        return true;

    }



    @Override
    public boolean editAdminInfoById(Integer id, String name, String phone) {
        Integer adminCountByPhone = adminMapper.getAdminCountByPhone(phone);
        if (StringUtils.isBlank(name)){
            buildError(BAD_REQUEST, "名字不能为空");
        }
        if (StringUtils.isBlank(phone)){
            buildError(BAD_REQUEST, "手机号不能为空");
        }
        if (adminCountByPhone > 1){
            buildError(BAD_REQUEST, "该手机号已存在");
        }
        if (PHONE_REGEX.matches(phone)) {
            buildError(BAD_REQUEST, "手机号格式不合法");
        }
        Admin admin = new Admin();
        admin.setId(id);
        admin.setName(name);
        admin.setPhone(phone);
        return adminMapper.updateAdminInfoById(admin);
    }

    @Override
    public boolean editAdminPwdById(Integer id, String oldPwd, String newPwd, String newPwdAgain) {
        Admin adminById = adminMapper.getAdminById(String.valueOf(id));
        if (StringUtils.isBlank(oldPwd)){
            buildError(BAD_REQUEST, "请输入原密码");
        }
        if (StringUtils.isBlank(newPwd)){
            buildError(BAD_REQUEST, "请输入新密码");
        }
        if (StringUtils.isBlank(newPwdAgain)){
            buildError(BAD_REQUEST, "请再次确认密码");
        }
        if (!adminById.getPassword().equals(oldPwd)){
            buildError(BAD_REQUEST, "请保证原密码正确");
        }
        if (!newPwd.equals(newPwdAgain)){
            buildError(BAD_REQUEST, "两次密码输入不一致");
        }
        Admin admin = new Admin();
        admin.setId(id);
        admin.setPassword(newPwd);
        return adminMapper.updateAdminPwdById(admin);
    }

    @Override
    public Table getNoticesByPage(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        Page<Announcement> page = (Page<Announcement>) announcementMapper.getAllNotices();
        Table noticeTable = new Table();
        noticeTable.setCount(page.getTotal());
        noticeTable.setData(page);
        return noticeTable;
    }


    @Override
    public Table getNoticesByPageAndKeyWords(Integer pageNum, Integer pageSize, String keyWords) {
        PageHelper.startPage(pageNum, pageSize);
        Page<Announcement> page = (Page<Announcement>) announcementMapper.getNoticesByKeyWords(keyWords);
        Table noticeTable = new Table();
        noticeTable.setCount(page.getTotal());
        noticeTable.setData(page);
        return noticeTable;
    }

    @Override
    public boolean addNotice (String title, String notice, Integer pushUserId){
        Admin adminById = adminMapper.getAdminById(pushUserId.toString());
        String pushUserName = adminById.getName();

        AddNoticeVo addNoticeVo = new AddNoticeVo();
        addNoticeVo.setTitle(title);
        addNoticeVo.setNotice(notice);
        addNoticeVo.setPushUserId(pushUserId);
        addNoticeVo.setPushUserName(pushUserName);

        return announcementMapper.addNotice(addNoticeVo);
    }


    @Override
    public boolean delNoticesByIds(Integer[] ids) {
        for (Integer id : ids) {
            announcementMapper.deleteNoticeById(id);
        }
        return true;
    }


    @Override
    public boolean delNoticeById(Integer id) {
        return announcementMapper.deleteNoticeById(id);
    }


    @Override
    public boolean editNoticeById(Integer id, String title, String notice, Integer pushUserId) {
        Admin adminById = adminMapper.getAdminById(pushUserId.toString());
        String pushUserName = adminById.getName();

            EditNoticeVo editNoticeVo = new EditNoticeVo();
            editNoticeVo.setId(id);
            editNoticeVo.setTitle(title);
            editNoticeVo.setNotice(notice);
            editNoticeVo.setPushUserId(pushUserId);
            editNoticeVo.setPushUserName(pushUserName);
        return announcementMapper.updateNoticeById(editNoticeVo);
    }

    @Override
    public Table getStudentsInfoByPage(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        Page<StudentTabInfo> page = (Page<StudentTabInfo>) studentMapper.getAllStudentInfo();
        Table stuTable = new Table();
        stuTable.setCount(page.getTotal());
        stuTable.setData(page);
        return stuTable;
    }

    @Override
    public Table getStudentsInfoByPageAndKeyWords(Integer pageNum, Integer pageSize, String keyWords) {
        PageHelper.startPage(pageNum, pageSize);
        Page<StudentTabInfo> page = (Page<StudentTabInfo>) studentMapper.getStudentInfoByKeyWords(keyWords);
        Table stuTable = new Table();
        stuTable.setCount(page.getTotal());
        stuTable.setData(page);
        return stuTable;
    }

    @Override
    public boolean addStudentInfo(Integer studyno, String password, String name, Integer genderId, String phone, Integer classId) {
        List<StudentTabInfo> allStudentInfo = studentMapper.getAllStudentInfo();
        List<Integer> studyNos = allStudentInfo.stream().map(studentTabInfo -> studentTabInfo.getStudyno()).collect(Collectors.toList());
        List<String> phones = allStudentInfo.stream().map(studentTabInfo -> studentTabInfo.getPhone()).collect(Collectors.toList());
        if (studyNos.contains(studyno)) {
            buildError(BAD_REQUEST, "该学号已存在");
        }
        if (phones.contains(phone)) {
            buildError(BAD_REQUEST, "该手机号已存在");
        }
        if (PHONE_REGEX.matches(phone)) {
            buildError(BAD_REQUEST, "手机号格式不合法");
        }
        Student student = new Student();
        student.setStudyno(studyno);
        student.setPassword(password);
        student.setName(name);
        String gender = genderId == 1 ? "男" : "女";
        student.setGender(gender);
        student.setPhone(phone);
        student.setClassId(classId);

            return studentMapper.addStudentInfo(student);
        }

    @Override
    @Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED, rollbackFor = {BusinessException.class})
    public boolean delStudentsInfoByIds(Integer[] ids) {
        try{
            for (Integer id : ids) {
                List<LeaveMsg> leaveMsgByStudentId = leaveMsgMapper.getLeaveMsgByStudentId(id);
                //删除所关联留言详情信息
                for (LeaveMsg leaveMsg : leaveMsgByStudentId) {
                    leaveMsgMapper.delLeaveMsgDetailIdByLeaveMsgId(leaveMsg.getId());
                }
                //删除所关联留言信息
                leaveMsgMapper.delLeaveMsgByStudentId(id);
                //删除所关联选择题答案信息
                answerMapper.delChoiceAnswerByStudentId(id);
                //删除所关联简答题答案信息
                answerMapper.delShortAnswerByStudentId(id);
                //删除所关联分数信息
                scoreMapper.delScoreByStudentId(id);
                //删除学生信息
                studentMapper.delStudentInfoById(id);
            }
            return true;
        }catch (Exception e){
            e.printStackTrace();
            System.out.println(e.getMessage());
            throw new BusinessException(HttpStatus.NOT_FOUND, e.getMessage());
        }
    }

    @Override
    @Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED, rollbackFor = {BusinessException.class})
    public boolean delStudentInfoById(Integer id) {
        try{
            List<LeaveMsg> leaveMsgByStudentId = leaveMsgMapper.getLeaveMsgByStudentId(id);
            //删除所关联留言详情信息
            for (LeaveMsg leaveMsg : leaveMsgByStudentId) {
                leaveMsgMapper.delLeaveMsgDetailIdByLeaveMsgId(leaveMsg.getId());
            }
            //删除所关联留言信息
            leaveMsgMapper.delLeaveMsgByStudentId(id);
            //删除所关联选择题答案信息
            answerMapper.delChoiceAnswerByStudentId(id);
            //删除所关联简答题答案信息
            answerMapper.delShortAnswerByStudentId(id);
            //删除所关联分数信息
            scoreMapper.delScoreByStudentId(id);
            //删除学生信息
            studentMapper.delStudentInfoById(id);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            System.out.println(e.getMessage());
            throw new BusinessException(HttpStatus.NOT_FOUND, e.getMessage());
        }
    }

    @Override
    public boolean editStudentInfoById(Integer id, Integer studyno, String password, String name, Integer genderId, String phone, Integer classId) {
        List<StudentTabInfo> allStudentInfo = studentMapper.getAllStudentInfo();
        for (StudentTabInfo studentTabInfo : allStudentInfo) {
            if (studentTabInfo.getStudyno().equals(studyno) && !studentTabInfo.getId().equals(id)) {
                buildError(BAD_REQUEST, "学号已存在");
            }
            if (!StringUtils.isBlank(studentTabInfo.getPhone())){
                if (studentTabInfo.getPhone().equals(phone) && !studentTabInfo.getId().equals(id)) {
                    buildError(BAD_REQUEST, "手机号已存在");
                }
            }
        }
        if (PHONE_REGEX.matches(phone)) {
            buildError(BAD_REQUEST, "手机号格式不合法");
        }
        Student student = new Student();
        student.setId(id);
        student.setStudyno(studyno);
        student.setPassword(password);
        student.setName(name);
        String gender = genderId == 1 ? "男" : "女";
        student.setGender(gender);
        student.setPhone(phone);
        student.setClassId(classId);
        return studentMapper.updateStudentInfoById(student);
    }

    @Override
    public List<Teacher> getAllTeachersInfo() {
        return teacherMapper.getAllTeacherInfo();
    }

    @Override
    public Table getTeachersInfoByPage(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        Page<Teacher> page = (Page<Teacher>) teacherMapper.getAllTeacherInfo();
        Table teaTable = new Table();
        teaTable.setCount(page.getTotal());
        teaTable.setData(page);
        return teaTable;
    }

    @Override
    public Table getTeachersInfoByPageAndKeyWords(Integer pageNum, Integer pageSize, String keyWords) {
        PageHelper.startPage(pageNum, pageSize);
        Page<Teacher> page = (Page<Teacher>) teacherMapper.getTeacherInfoByKeyWords(keyWords);
        Table teaTable = new Table();
        teaTable.setCount(page.getTotal());
        teaTable.setData(page);
        return teaTable;
    }

    @Override
    public boolean addTeacherInfo (Integer workno, String password, String name, Integer genderId, String phone){
        List<Teacher> allTeacherInfo = teacherMapper.getAllTeacherInfo();
        List<Integer> workNos = allTeacherInfo.stream().map(teacher -> teacher.getWorkno()).collect(Collectors.toList());
        List<String> phones = allTeacherInfo.stream().map(teacher -> teacher.getPhone()).collect(Collectors.toList());
        if (workNos.contains(workno)) {
            buildError(BAD_REQUEST, "工号已存在");
        }
        if (phones.contains(phone)) {
            buildError(BAD_REQUEST, "该手机号已存在");
        }
        if (PHONE_REGEX.matches(phone)) {
            buildError(BAD_REQUEST, "手机号格式不合法");
        }

        Teacher teacher = new Teacher();
        teacher.setWorkno(workno);
        teacher.setPassword(password);
        teacher.setName(name);
        String gender = genderId == 1 ? "男" : "女";
        teacher.setGender(gender);
        teacher.setPhone(phone);
        return teacherMapper.addTeacherInfo(teacher);
    }

    @Override
    @Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED, rollbackFor = {BusinessException.class})
    public boolean delTeachersInfoByIds(Integer[] ids) {
        try {
            for (Integer id : ids) {
                List<LeaveMsg> leaveMsgByTeacherId = leaveMsgMapper.getLeaveMsgByTeacherId(id);
                //删除所关联留言详情信息
                for (LeaveMsg leaveMsg : leaveMsgByTeacherId) {
                    leaveMsgMapper.delLeaveMsgDetailIdByLeaveMsgId(leaveMsg.getId());
                }
                //删除所关联留言信息
                leaveMsgMapper.delLeaveMsgByTeacherId(id);
                //删除所关联学习资料
                studyFileMapper.delStudyFileByTeacherId(id);
                //将所关联班级老师id置零
                classMsgMapper.resetClassTeacherIdByTeacherId(id);
                //删除所关联家庭作业
                List<Homework> homeWorkByTeacherId = homeworkMapper.getHomeWorkByTeacherId(id);
                for (Homework homework : homeWorkByTeacherId) {
                    homeworkService.deleteHomework(homework.getId());
                }
                //删除老师信息
                teacherMapper.delTeacherInfoById(id);
            }
            return true;
        }catch (Exception e){
            e.printStackTrace();
            System.out.println(e.getMessage());
            throw new BusinessException(HttpStatus.NOT_FOUND, e.getMessage());
        }
    }

    @Override
    @Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED, rollbackFor = {BusinessException.class})
    public boolean delTeacherInfoById(Integer id) {
        try{
            List<LeaveMsg> leaveMsgByTeacherId = leaveMsgMapper.getLeaveMsgByTeacherId(id);
            //删除所关联留言详情信息
            for (LeaveMsg leaveMsg : leaveMsgByTeacherId) {
                leaveMsgMapper.delLeaveMsgDetailIdByLeaveMsgId(leaveMsg.getId());
            }
            //删除所关联留言信息
            leaveMsgMapper.delLeaveMsgByTeacherId(id);
            //删除所关联学习资料
            studyFileMapper.delStudyFileByTeacherId(id);
            //将所关联班级老师id置零
            classMsgMapper.resetClassTeacherIdByTeacherId(id);
            //删除所关联家庭作业
            List<Homework> homeWorkByTeacherId = homeworkMapper.getHomeWorkByTeacherId(id);
            for (Homework homework : homeWorkByTeacherId) {
                homeworkService.deleteHomework(homework.getId());
            }
            //删除老师信息
            teacherMapper.delTeacherInfoById(id);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            System.out.println(e.getMessage());
            throw new BusinessException(HttpStatus.NOT_FOUND, e.getMessage());
        }
    }

    @Override
    public boolean editTeacherInfoById(Integer id, Integer workno, String password, String name, Integer genderId, String phone) {
        List<Teacher> allTeacherInfo = teacherMapper.getAllTeacherInfo();
        for (Teacher teacher : allTeacherInfo) {
            if (teacher.getWorkno().equals(workno) && !teacher.getId().equals(id)) {
                buildError(BAD_REQUEST, "工号已存在");
            }
            if (!StringUtils.isBlank(teacher.getPhone())){
                if (teacher.getPhone().equals(phone) && !teacher.getId().equals(id)) {
                    buildError(BAD_REQUEST, "手机号已存在");
                }
            }

        }
        if (PHONE_REGEX.matches(phone)) {
            buildError(BAD_REQUEST, "手机号格式不合法");
        }

        Teacher teacher = new Teacher();
        teacher.setId(id);
        teacher.setWorkno(workno);
        teacher.setPassword(password);
        teacher.setName(name);
        String gender = genderId == 1 ? "男" : "女";
        teacher.setGender(gender);
        teacher.setPhone(phone);
        return teacherMapper.updateTeacherInfoById(teacher);
    }

    @Override
    public List<ClassTabInfo> getAllClassMsg() {
        return classMsgMapper.getAllClassMsg();
    }

    @Override
    public Table getClassesInfoByPage(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        Page<ClassTabInfo> page = (Page<ClassTabInfo>) classMsgMapper.getAllClassMsg();
        Table claTable = new Table();
        claTable.setCount(page.getTotal());
        claTable.setData(page);
        return claTable;
    }

    @Override
    public Table getClassesInfoByPageAndKeyWords(Integer pageNum, Integer pageSize, String keyWords) {
        PageHelper.startPage(pageNum,pageSize);
        Page<ClassTabInfo> page = (Page<ClassTabInfo>) classMsgMapper.getClassMsgByKyWords(keyWords);
        Table claTable = new Table();
        claTable.setCount(page.getTotal());
        claTable.setData(page);
        return claTable;
    }

    @Override
    public boolean addClassInfo(String className, Integer teacherId) {
        List<ClassTabInfo> allClassMsg = classMsgMapper.getAllClassMsg();
        List<String> classNames = allClassMsg.stream().map(classMsg -> classMsg.getClassName()).collect(Collectors.toList());
        if (classNames.contains(className)) {
            buildError(BAD_REQUEST, "班级名称已存在");
        }
        ClassMsg classMsg = new ClassMsg();
        classMsg.setClassName(className);
        classMsg.setTeacherId(teacherId);
        return classMsgMapper.addClassMsgInfo(classMsg);
    }

    @Override
    public boolean editClassInfoById(Integer id, String className, Integer teacherId) {
        List<ClassTabInfo> allClassMsg = classMsgMapper.getAllClassMsg();
        for (ClassTabInfo classMsg : allClassMsg) {
            if (classMsg.getClassName().equals(className) && !classMsg.getId().equals(id)){
                buildError(BAD_REQUEST, "班级名称已存在");
            }
        }
        ClassMsg classMsg = new ClassMsg();
        classMsg.setId(id);
        classMsg.setClassName(className);
        classMsg.setTeacherId(teacherId);
        return classMsgMapper.updateClassMsgInfoById(classMsg);
    }
}


